package org.csu.mypetstorecmsapi.service;

import org.csu.mypetstorecmsapi.domain.SignOn;
import org.csu.mypetstorecmsapi.domain.User;
import org.csu.mypetstorecmsapi.persistence.SignOnDao;
import org.csu.mypetstorecmsapi.persistence.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService
{
    @Autowired
    private UserDao userDao;
    @Autowired
    private SignOnDao signOnDao;

    public List<User> getUsers()
    {
        List<User> users = userDao.findAll();
        for (User user : users){
            user.setPassword(signOnDao.findByUsername(user.getUsername()).getPassword());
        }
        return users;
    }

    public User getUserById(int id)
    {
        User user = userDao.findById(id).get();
        user.setPassword(signOnDao.findByUsername(user.getUsername()).getPassword());
        return user;
    }

    //检查用户名是否存在
    public boolean existByUsername(String username)
    {
        return !userDao.findByUsername(username).isEmpty();
    }

    public void addUser(User user)
    {
        userDao.save(user);
        SignOn signOn = new SignOn();
        signOn.setUsername(user.getUsername());
        signOn.setPassword(user.getPassword());
        signOnDao.save(signOn);
    }

    public void deleteUser(int id)
    {
        signOnDao.deleteByUsername(userDao.findById(id).get().getUsername());
        userDao.deleteById(id);
    }

    public void editUser(int id, User u)
    {
        userDao.findById(id).ifPresent(user -> {
            user.setUsername(u.getUsername());
            user.setEmail(u.getEmail());
            user.setFirstName(u.getFirstName());
            user.setLastName(u.getLastName());
            user.setStatus(u.getStatus());
            user.setAddress1(u.getAddress1());
            user.setAddress2(u.getAddress2());
            user.setCity(u.getCity());
            user.setState(u.getState());
            user.setZip(u.getZip());
            user.setCountry(u.getCountry());
            user.setPhone(u.getPhone());
            userDao.save(user);
        });

        SignOn signOn = signOnDao.findByUsername(u.getUsername());
        signOn.setUsername(u.getUsername());
        signOn.setPassword(u.getPassword());
        signOnDao.save(signOn);
    }
}
